// 引入axios
import axios, { AxiosRequestConfig } from "axios";
import { ElMessage } from "element-plus"
import { $go2 } from "../utils/routerUtil";
import { getRefreshToken } from "./api";


const request=axios.create({
    baseURL:"http://localhost:8086/",
    timeout:10000,
})

request.interceptors.request.use( config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        let token = window.localStorage.getItem("token");
        if (token) {
            config.headers.Authorization ="Bearer"+' '+ token;
        }
        return config;
    }, (err) => {
        return Promise.reject(err);
    }
);

request.interceptors.response.use(
    (response)=>response,
   async (error)=>{
    const {data}=await getRefreshToken()
    if(data.msg==="success"){
        window.localStorage.setItem("token",data.result.token);
        return axios(error.config);
    }else{
      $go2("/");
      ElMessage.error("刷新token失败,需要重新登录!");
      return;
    }
        
    }
)
export default request;